package com.project.smarthome.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.text.TextUtils;
import android.widget.Toast;

import com.project.smarthome.SmartApplication;
import com.sds.smarthome.business.domain.entity.UserInfo;
import com.sds.smarthome.business.domain.service.DomainFactory;
import com.sds.smarthome.business.domain.service.DomainService;
import com.sds.smarthome.business.event.GwUpgradResultEvent;
import com.sds.smarthome.business.event.LocationUpdateEvent;
import com.sds.smarthome.business.event.UserNeedLoginEvent;
import com.sds.smarthome.business.facade.weiju.DoorVideoHandler;
import com.sds.smarthome.foundation.util.XLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * android application引用的presenter
 */
public class ApplicationPresenter implements UIPresenter, ActivityObserver.AppCallback {

    private static final String APP_PRE = "smart_pre";
    private static final String StatusColor = "status_color";

    private static UIThread sUiThread;
    private static JobExecutor sJobExecutor;
    private static SharedPreferences sAppPre;
    private static ApplicationPresenter sInstance;
    private DomainService mService;//持有引用对象，防止被回收
    private Context mAppContext;
    private ActivityObserver mActivityObserver;
    private boolean isForeground;

    private ApplicationPresenter(Context context, ActivityObserver observer) {
        this.mActivityObserver = observer;
        this.mAppContext = context;
        sUiThread = new UIThread();
        sJobExecutor = new JobExecutor();
        mService = DomainFactory.getDomainService();
        mService.initService(context);
        this.mActivityObserver.setAppCallback(this);
        sAppPre = context.getSharedPreferences(APP_PRE, Context.MODE_PRIVATE);
        setUserClientId();
        EventBus.getDefault().register(this);
    }

    private void setUserClientId() {
        SharedPreferences sharedPreferences = SmartApplication.getContext().getSharedPreferences("SdsPushCid", Context.MODE_PRIVATE);
//        final String cid = sharedPreferences.getString(PushCid, null);
//        final int pushType = sharedPreferences.getInt(PushType, 0);
//        String clientId = PushServiceHandler.PushChan + "_" + pushType + "_" + cid;
//        DomainFactory.getUserService().setClientId(clientId);
//        UserInfo userInfo = mService.loadUserInfo();
//        if (userInfo != null)
//            XLog.setClientId("Android " + userInfo.getPhoneNum() + " " + clientId);
//        else
//            XLog.setClientId("Android " + clientId);

    }


    public static ApplicationPresenter initializeWithApp(Application app, ActivityObserver observer) {
        if (sInstance == null) {
            sInstance = new ApplicationPresenter(app, observer);
        }
        return sInstance;
    }

    public static ApplicationPresenter getsInstance() {
        return sInstance;
    }

    public Activity getTopActivity() {
        if (mActivityObserver != null) {
            return mActivityObserver.getmTopActivity();
        }

        return null;
    }

    static Scheduler getsJobExecutor() {
        return Schedulers.from(sJobExecutor);
    }

    static Scheduler getUiExecutor() {
        return sUiThread.getScheduler();
    }

//    public static int getStatusBarColor() {
//        int color = sAppPre.getInt(StatusColor, 0);
//        if (color == 0)
//            color = R.color.blue1;
//
//        return color;
//    }

    public static void setStatusBarColor(int colorId) {
        sAppPre.edit().putInt(StatusColor, colorId).commit();
    }

    @Override
    public void init() {
//        DoorVideoHandler.setIncomingCallback(new DoorVideoHandler.WeijuIncomingCallback() {
//            @Override
//            public void callIncoming() {
//                Intent callIntent = new Intent(mAppContext, WeijuCallActivity.class);
//                callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                mAppContext.startActivity(callIntent);
//            }
//        });
//        UserInfo userInfo = mService.loadUserInfo();
//        if (userInfo != null) {
//            DoorVideoHandler.init(userInfo.getId(), userInfo.getPhoneNum(), mAppContext);
//        } else {
//            DoorVideoHandler.init(null, null, mAppContext);
//        }
    }

//
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onDevCancelShareEvent(final DevCancelShareEvent event) {
//        Observable observable1 = Observable.create(new Observable.OnSubscribe<Boolean>() {
//            @Override
//            public void call(Subscriber<? super Boolean> subscriber) {
//                boolean success = getUserService().syncUserSmartDev();
//                subscriber.onNext(success);
//            }
//        });
//        observable1.subscribeOn(getsJobExecutor())
//                .observeOn(getUiExecutor())
//                .subscribe(new Action1<Boolean>() {
//                    @Override
//                    public void call(Boolean success) {
//                        if (success) {
//                            mService.removeSmartDevice(event.getDevId());
//                            RemindDialog dialog = new RemindDialog(mActivityObserver.getmTopActivity());
//                            dialog.setRemindOnclick(new RemindDialog.RemindOnclick() {
//                                @Override
//                                public void sure() {
//                                    Intent intent = new Intent();
//                                    intent.setClass(mActivityObserver.getmTopActivity(), MainActivity.class);
//                                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
//                                    mActivityObserver.getmTopActivity().startActivity(intent);
//                                    EventBus.getDefault().post(new SmartDevRemovedEvent(event.getDevId()));
//                                }
//                            });
//                            dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//                            dialog.getDialog(mActivityObserver.getmTopActivity(), "分享设备的权限已变更", true);
//                            filterLimitDialog(dialog);
//                        }
//                    }
//                });
//    }
//
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onDevShareAddEvent(final DevShareAddEvent event) {
//        Observable observable1 = Observable.create(new Observable.OnSubscribe<Boolean>() {
//            @Override
//            public void call(Subscriber<? super Boolean> subscriber) {
//                mService.updateSmartDevShareUsers(event.getDevId(), event.getUserId());
//                subscriber.onNext(true);
//            }
//        });
//        observable1.subscribeOn(getsJobExecutor())
//                .observeOn(getUiExecutor())
//                .subscribe(new Action1<Boolean>() {
//                    @Override
//                    public void call(Boolean success) {
//                        String phoneNum = event.getPhoneNum();
//                        final String devId = event.getDevId();
//
//                        RemindNoTitleDialog dialog = new RemindNoTitleDialog(mActivityObserver.getmTopActivity());
//                        dialog.seteditDialogListener(new RemindNoTitleDialog.MessageDialogListener() {
//                            @Override
//                            public void sure() {
//                                ViewNavigator.navToUserManage(new ToUserManageNavEvent(devId));
//                                EventBus.getDefault().post(new FinishActivityEvent());
//                            }
//
//                            @Override
//                            public void cancel() {
//                                EventBus.getDefault().post(new FinishActivityEvent());
//                            }
//                        });
//                        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//                        dialog.getDialog(mActivityObserver.getmTopActivity(), "您分享的设备已经被用户" + phoneNum + "添加\n", "授权", "知道了", true);
//                        filterShareDviceAdd(dialog);
//                    }  //  #3849 android.view.WindowManager$BadTokenException
//                });
//    }

//    private void filterShareDviceAdd(RemindNoTitleDialog dialog) {
//        if (mShareDviceAddDialogs != null && !mShareDviceAddDialogs.isEmpty()) {
//            for (RemindNoTitleDialog dialog1 : mShareDviceAddDialogs) {
//                if (dialog1 != null) {
//                    dialog1.dissMissDialog();
//                }
//            }
//            mShareDviceAddDialogs.clear();
//        }
//        if (mShareDviceAddDialogs == null) {
//            mShareDviceAddDialogs = new ArrayList<>();
//        }
//        mShareDviceAddDialogs.add(dialog);
//    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onDevShareChangeEvent(final DevShareChangeEvent event) {
//        Observable observable1 = Observable.create(new Observable.OnSubscribe<Boolean>() {
//            @Override
//            public void call(Subscriber<? super Boolean> subscriber) {
//                UserInfo userInfo = mService.loadUserInfo();
//                if (userInfo != null)
//                    getUserService().checkLocalTokenExpired();
//                subscriber.onNext(true);
//            }
//        });
//        observable1.subscribeOn(getsJobExecutor())
//                .observeOn(getUiExecutor())
//                .subscribe(new Action1<Boolean>() {
//                    @Override
//                    public void call(Boolean success) {
//                        RemindDialog dialog = new RemindDialog(mActivityObserver.getmTopActivity());
//                        dialog.setRemindOnclick(new RemindDialog.RemindOnclick() {
//                            @Override
//                            public void sure() {
//                                Intent intent = new Intent();
//                                intent.setClass(mActivityObserver.getmTopActivity(), MainActivity.class);
//                                intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
//                                mActivityObserver.getmTopActivity().startActivity(intent);
//                                EventBus.getDefault().post(new SmartCenterToHomeEvent(event.getDevId(), false));
//                            }
//                        });
//                        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//                        dialog.getDialog(mActivityObserver.getmTopActivity(), "分享设备的权限已变更", true);
//                        filterLimitDialog(dialog);
//                    }
//                });
//    }
//
//    private void filterLimitDialog(RemindDialog dialog) {
//        if (mLimitDialogs != null && !mLimitDialogs.isEmpty()) {
//            for (RemindDialog dialog1 : mLimitDialogs) {
//                if (dialog1 != null) {
//                    dialog1.dissMissDialog();
//                }
//            }
//            mLimitDialogs.clear();
//        }
//        if (mLimitDialogs == null) {
//            mLimitDialogs = new ArrayList<>();
//        }
//        mLimitDialogs.add(dialog);
//    }
//
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onTokenExpiredEvent(final TokenExpiredEvent event) {
//        UserInfo userInfo = mService.loadUserInfo();
//        if (userInfo == null)
//            return;
//        String curToken = userInfo.getToken();
//        if (TextUtils.equals(event.getToken(), curToken)) {
//            PushServiceHandler.notifyUser("您的账号已经于" + event.getLoginTime() + "在其他终端进行登录", 2);
//            DoorVideoHandler.destroy();
//            mService.clearCache();
//            mService.destorySmartDevice();
//            SmartPushService.stopPushService(mActivityObserver.getmTopActivity());
//            EZPlayerFloatVideoView.close();
//            mDialog = new RemindDialog(mActivityObserver.getmTopActivity());
//            mDialog.setRemindOnclick(new RemindDialog.RemindOnclick() {
//                @Override
//                public void sure() {
//                    MainHandler.cancelAll();
//                    Intent intent = new Intent();
//                    intent.setClass(mActivityObserver.getmTopActivity(), LoginActivity.class);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                    mActivityObserver.getmTopActivity().startActivity(intent);
//                }
//            });
//            mDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//            mDialog.getDialog(mActivityObserver.getmTopActivity(), "您的账号已在其他设备登陆，请重新登陆", true);
//        }
//    }

//    private void filterOtherLogin(RemindDialog dialog) {
//        if (mOtherLoginDialogs != null && !mOtherLoginDialogs.isEmpty()) {
//            for (RemindDialog dialog1 : mOtherLoginDialogs) {
//                if (dialog1 != null) {
//                    dialog.dissMissDialog();
//                }
//            }
//            mOtherLoginDialogs.clear();
//        }
//        if (mOtherLoginDialogs == null) {
//            mOtherLoginDialogs = new ArrayList<>();
//        }
//        mOtherLoginDialogs.add(dialog);
//    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onDevCancelEvent(final DevCancelEvent event) {
//        RemindDialog dialog = new RemindDialog(mActivityObserver.getmTopActivity());
//        if (mActivityObserver.getmTopActivity() != null && !mActivityObserver.getmTopActivity().isFinishing()) {
//            dialog.getDialog(mActivityObserver.getmTopActivity(), "您分享的设备已经被用户解绑");
//            filterShareDviceDel(dialog);
//        }
//    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGwUpgradResultEvent(final GwUpgradResultEvent event) {

        if (TextUtils.equals(mService.loadCurCCuId(), event.getCcuId())) {
            String name = mService.getGwNameById(event.getDeviceId());
            if (mActivityObserver.getmTopActivity() instanceof BaseActivity) {
                Toast.makeText(mActivityObserver.getmTopActivity(),
                        "网关" + name + "升级" + (event.isSuccess() ? "成功" : "失败"), Toast.LENGTH_SHORT).show();
            }
        }
    }

//    @Subscribe(threadMode = ThreadMode.BACKGROUND)
//    public void onCodelibUploadResultEvent(final CodelibUploadResultEvent event) {
//
//        if (TextUtils.equals(mService.loadCurCCuId(), event.getCcuId())) {
//            if (!mService.isOwner()) {
//                return;
//            }
//
//            final int devId = event.getDeviceId();
//            final Device device = DomainFactory.getCcuHostService().getContext(event.getCcuId()).findDeviceById(devId, UniformDeviceType.ZIGBEE_InfraredCodeLib);
//            if (device == null) {
//                return;
//            }
//            final String roomName = new SmartHomeService().getRoomName(event.getCcuId(), device.getRoomId());
//
//            if (event.isSuccess()) {
//                MainHandler.runInMainThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        SosDialog sosDialog = new SosDialog(mActivityObserver.getmTopActivity());
//                        if (mActivityObserver.getmTopActivity() != null && !mActivityObserver.getmTopActivity().isFinishing()) {
//                            sosDialog.getDialog(mActivityObserver.getmTopActivity(), roomName + device.getName() + "的码库下载成功!", "我知道了");
//                            filterCodeLibSeccussDialog(sosDialog);
//                        }
//                    }
//                });
//            } else {
//                MainHandler.runInMainThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        RemindNoTitleDialog dialog = new RemindNoTitleDialog(mActivityObserver.getmTopActivity());
//                        dialog.seteditDialogListener(new RemindNoTitleDialog.MessageDialogListener() {
//                            @Override
//                            public void sure() {
//                                ToDeviceEditNavEvent editNavEvent = new ToDeviceEditNavEvent(false, devId + "", device.getRoomId(), UniformDeviceType.ZIGBEE_InfraredCodeLib);
//                                editNavEvent.setHostId(event.getCcuId());
//                                editNavEvent.setRoomName(roomName);
//                                editNavEvent.setDeviceName(device.getName());
//                                ViewNavigator.navToInfraredEdit(editNavEvent);
//                            }
//
//                            @Override
//                            public void cancel() {
//
//                            }
//                        });
//                        if (mActivityObserver.getmTopActivity() != null && !mActivityObserver.getmTopActivity().isFinishing()) {
//                            dialog.getDialog(mActivityObserver.getmTopActivity(), roomName + device.getName() + "的码库加载失败,\n请重新配置!", "确定", "取消");
//                            filterCodeLibDialog(dialog);
//                        }
//                    }
//                });
//            }
//        }
//    }



    @Override
    public void onAppForeground(long backTime) {
        XLog.f("app 进入前台");
        isForeground = true;
        checkNeedShowGesture(backTime);
        checkUserTokenExpired();
        getLocation();
    }

    private void getLocation() {
        LocationManager locManager = (LocationManager) SmartApplication.getContext().getSystemService(Context.LOCATION_SERVICE);
        if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            DomainFactory.getDomainService().setCurLocation("杭州市");
            EventBus.getDefault().post(new LocationUpdateEvent("杭州市"));
        } else {
            DomainFactory.getDomainService().initLocationSevice(SmartApplication.getContext());
        }
    }


    public void checkUserTokenExpired() {
//        if ((mActivityObserver.getmTopActivity() instanceof WelcomeActivity ||
//                mActivityObserver.getmTopActivity() instanceof LoginActivity ||
//                mActivityObserver.getmTopActivity() instanceof RegistActivity ||
//                mActivityObserver.getmTopActivity() instanceof PassWordActivity
//                || (!SmartApplication.sIsnormalstart && mActivityObserver.getmTopActivity() instanceof MainActivity))) {
//            return;
//        }
//        if (mService.loadUserInfo() == null) {
//            if (mDialog == null) {
//                mDialog = new RemindDialog(SmartApplication.getContext());
//                mDialog.setRemindOnclick(new RemindDialog.RemindOnclick() {
//                    @Override
//                    public void sure() {
//                        MainHandler.cancelAll();
//                        Intent intent = new Intent();
//                        intent.setClass(mActivityObserver.getmTopActivity(), LoginActivity.class);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                        mActivityObserver.getmTopActivity().startActivity(intent);
//                    }
//                });
//                mDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//            }
//            if (mDialog.isShowing()) {
//                mDialog.dismiss();
//            }
//            mDialog.getDialog(SmartApplication.getContext(), "您的账号已在其他设备登陆，请重新登陆", "");
//        }
//
//        WorkHandler.run(new Runnable() {
//            @Override
//            public void run() {
//                boolean expired = DomainFactory.getUserService().checkLocalTokenExpired();
//                if (!expired || (!SmartApplication.sIsnormalstart)) {
//                    EventBus.getDefault().post(new AppForegroundEvent());
//                }
//            }
//        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUserNeedLoginEvent(final UserNeedLoginEvent event) {

        UserInfo userInfo = mService.loadUserInfo();
        if (userInfo == null) {
            return;
        }

        Toast.makeText(mActivityObserver.getmTopActivity(), "用户未认证，请重新登录", Toast.LENGTH_SHORT).show();

        DoorVideoHandler.destroy();
        mService.clearCache();
        mService.destorySmartDevice();

//        com.project.smarthome.common.util.MainHandler.cancelAll();
        Intent intent = new Intent();
//        intent.setClass(mActivityObserver.getmTopActivity(), LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        mActivityObserver.getmTopActivity().startActivity(intent);
    }

    @Override
    public void onAppBackground() {
        XLog.f("app 进入后台");
        isForeground = false;
    }

    private void checkNeedShowGesture(long backTime) {
//        if (mActivityObserver.getmTopActivity() instanceof com.project.smarthome.base.NoUserAuthorize) {
//            return;
//        }
//        UserInfo userInfo = mService.loadUserInfo();
//        if (userInfo == null) {
//            return;
//        }
//        GestureSet gestureSet = mService.getGestureSet();
//
//        if (gestureSet != null && gestureSet.isOpen() && backTime >= 5 * 1000) {
//            Intent intent = new Intent(SmartApplication.getContext(),
//                    GestureVerActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            SmartApplication.getContext().startActivity(intent);
//        }
    }

    private static class UIThread {

        public UIThread() {
        }

        public Scheduler getScheduler() {
            return AndroidSchedulers.mainThread();
        }
    }

    private static class JobExecutor implements Executor {

        private static final int INITIAL_POOL_SIZE = 2;
        private static final int MAX_POOL_SIZE = 5;
        private static final int KEEP_ALIVE_TIME = 10;
        private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;

        private final BlockingQueue<Runnable> mWorkQueue;

        private final ThreadPoolExecutor mThreadpoolexecutor;

        private final ThreadFactory mThreadfactory;

        JobExecutor() {
            this.mWorkQueue = new LinkedBlockingQueue<>();
            this.mThreadfactory = new JobThreadFactory();
            this.mThreadpoolexecutor = new ThreadPoolExecutor(INITIAL_POOL_SIZE, MAX_POOL_SIZE,
                    KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, this.mWorkQueue, this.mThreadfactory);
        }

        @Override
        public void execute(Runnable runnable) {
            if (runnable == null) {
                throw new IllegalArgumentException("Runnable to execute cannot be null");
            }
            this.mThreadpoolexecutor.execute(runnable);
        }

        public void destroy() {
            mThreadpoolexecutor.shutdownNow();
        }

        private static class JobThreadFactory implements ThreadFactory {
            private static final String THREAD_NAME = "android_";
            private int counter = 0;

            @Override
            public Thread newThread(Runnable runnable) {
                return new Thread(runnable, THREAD_NAME + counter++);
            }
        }
    }

    @Override
    public void destroy() {
        sJobExecutor.destroy();
        EventBus.getDefault().unregister(this);
    }

}

